//
//  WordsViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/4/19.
//

#import "WordsViewController.h"
#import "MessageViewController.h"
#import "BookListViewController.h"
#import "CourseListViewController.h"
#import "BookListModel.h"
#import "FSPagerViewObjcCompat.h"
#import "MyBookListManager.h"
#import "MyBookListModel.h"
#import "TestSubmitAlertView.h"
#import "DeleteBookManager.h"
#import "LoginViewController.h"
#import "StudyCalendarViewController.h"
#import "CountDownSelView.h"
#import "GetUserInfoManager.h"
#import "MineUserModel.h"
#import "EditUserInfoManager.h"
#import "DownTimeManager.h"
#import "SearchViewController.h"
#import "TestWordChooseCourseViewController.h"
#import "NewsCheckManager.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import "GetALiYunTokenManager.h"
#import "NewsListManager.h"
#import "NewsListModel.h"
#import "MessageAlertView.h"

@interface WordsViewController ()<JPAPIManagerCallBackDelegate,FSPagerViewDataSource,FSPagerViewDelegate>

@property(nonatomic,strong)UILabel *countDownTipLabel;
@property(nonatomic,strong)UILabel *dayLabel;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UILabel *precentLabel;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)UIProgressView *progressView;
@property(nonatomic,strong)UILabel *bookNameLabel;
@property(nonatomic,strong)FSPagerView *pagerView;
@property(nonatomic,strong)NSMutableArray *bookArr;
@property(nonatomic,strong)MyBookListManager *myBookListManager;
@property(nonatomic,strong)TestSubmitAlertView *deleteAlertView;
@property(nonatomic,strong)DeleteBookManager *deleteBookManager;
@property(nonatomic,strong)MyBookListModel *currentBookModel;
@property(nonatomic,strong)UIButton *addBtn;
@property(nonatomic,strong)CALayer *addShadowLayer;
@property(nonatomic,strong)UIImageView *emptyImageView;
@property(nonatomic,strong)CountDownSelView *countDownSelView;
@property(nonatomic,strong)GetUserInfoManager *userInfoManager;
@property(nonatomic,strong)MineUserModel *userModel;
@property(nonatomic,strong)EditUserInfoManager *editManager;
@property(nonatomic,strong)DownTimeManager *downTimeManager;
@property(nonatomic,assign)NSInteger book_index;
@property(nonatomic,strong)NewsCheckManager *newsCheckManager;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)UIView *point;
@property (nonatomic,assign)SCNetworkReachabilityRef reachability;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)NewsListManager *msgListManager;
@property(nonatomic,strong)MessageAlertView *messageAlertView;
@property(nonatomic,strong)UIImageView *topBgImageView;

@end

@implementation WordsViewController


-(MyBookListManager *)myBookListManager{
    if(!_myBookListManager){
        _myBookListManager = [[MyBookListManager alloc]init];
        _myBookListManager.delegate = self;
    }
    return _myBookListManager;
}

-(NSMutableArray *)bookArr{
    if(!_bookArr){
        _bookArr = [NSMutableArray array];
    }
    return _bookArr;
}

-(DeleteBookManager *)deleteBookManager{
    if(!_deleteBookManager){
        _deleteBookManager = [[DeleteBookManager alloc]init];
        _deleteBookManager.delegate = self;
    }
    return _deleteBookManager;
}

-(GetUserInfoManager *)userInfoManager{
    if(!_userInfoManager){
        _userInfoManager = [[GetUserInfoManager alloc]init];
        _userInfoManager.delegate = self;
    }
    return _userInfoManager;
}

-(EditUserInfoManager *)editManager{
    if(!_editManager){
        _editManager = [[EditUserInfoManager alloc]init];
        _editManager.delegate = self;
    }
    return _editManager;
}

-(DownTimeManager *)downTimeManager{
    if(!_downTimeManager){
        _downTimeManager = [[DownTimeManager alloc]init];
        _downTimeManager.delegate = self;
    }
    return _downTimeManager;
}

-(NewsCheckManager *)newsCheckManager{
    if(!_newsCheckManager){
        _newsCheckManager = [[NewsCheckManager alloc]init];
        _newsCheckManager.delegate = self;
    }
    return _newsCheckManager;
}

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}

-(NewsListManager *)msgListManager{
    if(!_msgListManager){
        _msgListManager = [[NewsListManager alloc]init];
        _msgListManager.delegate = self;
    }
    return _msgListManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        [self getUserInfo];
        [self loadBookData];
        [self loadMsgData];
        if(!self.timer){
            self.timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
        }else{
            //开启定时器
            [self.timer setFireDate:[NSDate distantPast]];
        }
    }else{
        [self getDownTimeData];
    }
    
    if ([self isFirstLaunch]) {
        // 仅在首次启动时设置网络监听
        [self startNetworkReachability];
    }
    
    //检查语音token
    [self checkToken];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addBookSuccess) name:@"AddBookSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess:) name:@"loginSuccess" object:nil];
        
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationWillEnterForeground)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(wordProgessUpdate) name:@"WordProgessUpdate" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(messageUpdate) name:@"messageUpdate" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(messageClear) name:@"messageClear" object:nil];
    

    
}

#pragma mark - 获取消息列表 取最新那条消息弹窗显示
-(void)loadMsgData{
    self.msgListManager.page = @"1";
    [self.msgListManager loadData];
}

#pragma mark - 清除所有消息
-(void)messageClear{
    self.point.hidden = YES;
}

#pragma mark - 消息已读更新
-(void)messageUpdate{
    [self.newsCheckManager loadData];
}

#pragma mark - 判断是否是首次启动
- (BOOL)isFirstLaunch {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults boolForKey:@"hasLaunchedOnce"]) {
        [defaults setBool:YES forKey:@"hasLaunchedOnce"];
        [defaults synchronize];
        return YES;
    }
    return NO;
}

#pragma mark - 开始网络状态监听
- (void)startNetworkReachability {
    NSString *remoteHostName = @"www.apple.com";
    self.reachability = SCNetworkReachabilityCreateWithName(NULL, [remoteHostName UTF8String]);
    
    SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
    SCNetworkReachabilitySetCallback(self.reachability, ReachabilityCallback, &context);
    SCNetworkReachabilityScheduleWithRunLoop(self.reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}

static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) {
    WordsViewController *self = (__bridge WordsViewController *)info;
    [self reachabilityChanged:flags];
}

- (void)reachabilityChanged:(SCNetworkReachabilityFlags)flags {
    BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkReachabilityFlagsConnectionRequired;
    
    if (isReachable && !needsConnection) {
        // 网络可达，获取数据
        [self getDownTimeData];
        
        [self checkToken];
        
        // 停止监听
        SCNetworkReachabilityUnscheduleFromRunLoop(self.reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
        CFRelease(self.reachability);
        self.reachability = nil;
    }
}

#pragma mark - 获取是否有新消息
-(void)updateTime{
    [self.newsCheckManager loadData];
}

#pragma mark - 单词学习过进度刷新
-(void)wordProgessUpdate{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        self.book_index = self.pagerView.currentIndex;
        [self.bookArr removeAllObjects];
        [self loadBookData];
    }
}

#pragma mark - app回到前台
-(void)applicationWillEnterForeground{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        [self getUserInfo];
    }
    [self checkToken];
}

#pragma mark - 没有登录的时候获取系统倒计时
-(void)getDownTimeData{
    [self.downTimeManager loadData];
}

#pragma mark - 获取个人信息
-(void)getUserInfo{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        self.userInfoManager.userId = userId;
        [self.userInfoManager loadData];
    }
}

#pragma mark - 登录过期
-(void)needLogin{
    if([[self currentViewController] isKindOfClass:[WordsViewController class]]){
        if(self.userModel){
            self.userModel = nil;
        }
        [self refreshCountDownUI];
        [self refreshAddBookView];
        [self getDownTimeData];
    }
    self.point.hidden = YES;
    if(self.timer){
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark - 登录成功
-(void)loginSuccess:(NSNotification*)notifi{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        [self getUserInfo];
        [self.bookArr removeAllObjects];
        [self loadBookData];
        if(!self.timer){
            self.timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
        }else{
            //开启定时器
            [self.timer setFireDate:[NSDate distantPast]];
        }
    }
}

#pragma mark - 退出登录成功
-(void)logoutSuccess{
    if(self.userModel){
        self.userModel = nil;
    }
    [self refreshCountDownUI];
    [self refreshAddBookView];
    [self getDownTimeData];
    self.point.hidden = YES;
    if(self.timer){
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark - 添加书本成功
-(void)addBookSuccess{
    [self.bookArr removeAllObjects];
    [self loadBookData];
}

#pragma mark - 获取我的书本
-(void)loadBookData{
    [self.myBookListManager loadData];
}

#pragma mark - 创建界面
-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];

    UIImageView *topBgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableWidth)];
    topBgImageView.backgroundColor = [UIColor clearColor];
    topBgImageView.image = [UIImage imageNamed:@"word_topbg"];
    topBgImageView.userInteractionEnabled = YES;
    [self.view addSubview:topBgImageView];
    self.topBgImageView = topBgImageView;
    
    
    UIButton *calendarBtn = [[UIButton alloc]init];
    [calendarBtn setImage:[UIImage imageNamed:@"word_calendar_logo"] forState:UIControlStateNormal];
    calendarBtn.adjustsImageWhenHighlighted = NO;
    [calendarBtn addTarget:self action:@selector(calendarBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:calendarBtn];
    [calendarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@38);
        make.left.mas_equalTo(@22);
        make.bottom.mas_equalTo(@-3);
    }];
    
    UIButton *msgBtn = [[UIButton alloc]init];
    [msgBtn setImage:[UIImage imageNamed:@"word_message_logo"] forState:UIControlStateNormal];
    msgBtn.adjustsImageWhenHighlighted = NO;
    [msgBtn addTarget:self action:@selector(msgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:msgBtn];
    [msgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@38);
        make.right.mas_equalTo(@-22);
        make.bottom.mas_equalTo(@-3);
    }];
    self.point = [[UIView alloc]init];
    self.point.backgroundColor = UIColorHex(0xFE4A4B);
    self.point.layer.cornerRadius = 4;
    self.point.layer.masksToBounds = YES;
    [self.customNavigationBar addSubview:self.point];
    [self.point mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(msgBtn.mas_right).offset(-12);
        make.top.mas_equalTo(msgBtn.mas_top).offset(5);
        make.width.height.mas_equalTo(@8);
    }];
    self.point.hidden = YES;
    
    UIButton *searchBtn = [[UIButton alloc]init];
    [searchBtn setImage:[UIImage imageNamed:@"word_search_logo"] forState:UIControlStateNormal];
    searchBtn.adjustsImageWhenHighlighted = NO;
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@38);
        make.right.mas_equalTo(msgBtn.mas_left);
        make.bottom.mas_equalTo(@-3);
    }];
    
    UIView *countDownBgView = [[UIView alloc]init];
    countDownBgView.backgroundColor = UIColorHex_(0xffffff,0.4);
    countDownBgView.layer.cornerRadius = 20;
    countDownBgView.layer.masksToBounds = YES;
    [self.view addSubview:countDownBgView];
    [countDownBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+10);
        make.left.mas_equalTo(@27);
        make.right.mas_equalTo(@-27);
        make.height.mas_equalTo(@134);
    }];
    __weak typeof(self)weakSelf = self;
    UITapGestureRecognizer *countDownTap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        if(userId){
            [weakSelf showTimeSelView];
        }else{
            [weakSelf login];
        }
    }];
    [countDownBgView addGestureRecognizer:countDownTap];
    
    self.countDownTipLabel = [[UILabel alloc]init];
    self.countDownTipLabel.font = JPUIFontPingFangSCMedium(20);
    self.countDownTipLabel.textColor = [UIColor blackColor];
    self.countDownTipLabel.textAlignment = NSTextAlignmentCenter;
    self.countDownTipLabel.backgroundColor = [UIColor clearColor];
    self.countDownTipLabel.userInteractionEnabled = YES;
    NSString *downTimeName = [[NSUserDefaults standardUserDefaults]objectForKey:@"downTimeName"];
    self.countDownTipLabel.text = downTimeName?downTimeName:@"";
    [countDownBgView addSubview:self.countDownTipLabel];
    [self.countDownTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(@16);
        make.height.mas_equalTo(@28);
    }];
    self.dayLabel = [[UILabel alloc]init];
    self.dayLabel.textAlignment = NSTextAlignmentCenter;
    self.dayLabel.backgroundColor = [UIColor clearColor];
    self.dayLabel.userInteractionEnabled = YES;
    NSString *downTimeCount = [[NSUserDefaults standardUserDefaults]objectForKey:@"downTimeCount"];
    self.dayLabel.attributedText = [self changeStr:downTimeCount?downTimeCount:@"0"];
    [countDownBgView addSubview:self.dayLabel];
    [self.dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@60);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(@43);
    }];
    self.timeLabel = [[UILabel alloc]init];
    self.timeLabel.font = JPUIFontPingFangSCMedium(13);
    self.timeLabel.textColor = [UIColor blackColor];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.backgroundColor = [UIColor clearColor];
    self.timeLabel.userInteractionEnabled = YES;
    NSString *downTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"downTime"];
    self.timeLabel.text = downTime?downTime:@"";
    [countDownBgView addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@18);
        make.top.mas_equalTo(@99);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
    }];
    
    CGFloat logo_w = [DeviceUtils getAdaptedWidthForDesignWidth:59 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(isIPAD&&logo_w > 59){
        logo_w = 59;
    }
    CGFloat pager_h = [DeviceUtils getAdaptedWidthForDesignWidth:255 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat pager_w = [DeviceUtils getAdaptedWidthForDesignWidth:197 andCurrentAvailableWidth:self.currentAvailableWidth];
    if((self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-171-37-logo_w-37-88) < pager_h){
        pager_h = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-171-37-logo_w-37-88;
        pager_w = 197*pager_h/255;
    }
    self.pagerView = [[FSPagerView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+171,self.currentAvailableWidth,pager_h)];
    self.pagerView.backgroundColor = [UIColor clearColor];
    self.pagerView.delegate = self;
    self.pagerView.dataSource = self;
    [self.pagerView registerClass:[FSPagerViewCell class] forCellWithReuseIdentifier:@"BookCell"];
    self.pagerView.isInfinite = NO;
    self.pagerView.transformer = [[FSPagerViewTransformer alloc]initWithType:FSPagerViewTransformerTypeLinear];
    self.pagerView.itemSize = CGSizeMake(pager_w,pager_h); // 调整每个图像的大小
    [self.view addSubview:self.pagerView];
    self.pagerView.hidden = YES;
    
    __weak typeof(self)self_weak_ = self;
    CGFloat book_name_w = [DeviceUtils getAdaptedWidthForDesignWidth:240 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.bookNameLabel = [[UILabel alloc]init];
    self.bookNameLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.bookNameLabel];
    [self.bookNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+171+pager_h+32);
        make.height.mas_equalTo(@24);
        make.width.mas_equalTo(book_name_w);
        make.centerX.mas_equalTo(self_weak_.view);
    }];
    self.bookNameLabel.hidden = YES;
    
    CGFloat progress_w = [DeviceUtils getAdaptedWidthForDesignWidth:200 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.progressView = [[UIProgressView alloc]init];
    self.progressView.progressTintColor = KThemeColor;
    self.progressView.backgroundColor = KbgColor;
    self.progressView.trackTintColor = KbgColor;
    self.progressView.layer.cornerRadius = 2;
    self.progressView.layer.shadowColor = UIColorHex_(0x000000,0.17).CGColor;
    self.progressView.layer.shadowOffset = CGSizeMake(0,0);
    self.progressView.layer.shadowOpacity = 1;
    self.progressView.layer.shadowRadius = 4;
    [self.view addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(progress_w);
        make.centerX.mas_equalTo(self_weak_.view);
        make.height.mas_equalTo(@4);
        make.top.mas_equalTo(self_weak_.bookNameLabel.mas_bottom).offset(6);
    }];
    self.progressView.hidden = YES;
    
    self.precentLabel = [[UILabel alloc]init];
    self.precentLabel.font = JPUIFontPingFangSCRegular(10);
    self.precentLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.precentLabel];
    [self.precentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self_weak_.progressView.mas_left);
        make.height.mas_equalTo(@14);
        make.top.mas_equalTo(self_weak_.progressView.mas_bottom).offset(4);
    }];
    self.precentLabel.hidden = YES;
    
    self.countLabel = [[UILabel alloc]init];
    self.countLabel.font = JPUIFontPingFangSCRegular(10);
    self.countLabel.textColor = KFontGrayColor;
    self.countLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:self.countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self_weak_.progressView.mas_right);
        make.height.mas_equalTo(@14);
        make.centerY.mas_equalTo(self_weak_.precentLabel);
    }];
    self.countLabel.hidden = YES;
  
    CGFloat left = (self.currentAvailableWidth-logo_w*4)/2.0;
    NSArray *imageArr = @[@"word_delete_logo",@"word_recite_logo",@"word_test_logo",@"word_add_logo"];
    for(NSInteger i = 0;i < imageArr.count;i++){
        UIButton *btn = [[UIButton alloc]init];
        [btn setBackgroundImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        btn.tag = 233+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(left+i*logo_w);
            make.height.width.mas_equalTo(logo_w);
            make.top.mas_equalTo(self_weak_.progressView.mas_bottom).offset(37);
        }];
        btn.hidden = YES;
    }
    
    CGFloat empty_w = [DeviceUtils getAdaptedWidthForDesignWidth:300 andCurrentAvailableWidth:self.currentAvailableWidth];
    if((self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-144-36-42-55-36) < empty_w){
        empty_w = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-144-36-42-55-36;
    }
    self.emptyImageView = [[UIImageView alloc]init];
    self.emptyImageView.image = [UIImage imageNamed:@"home_empty_logo"];
    [self.view addSubview:self.emptyImageView];
    [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(empty_w);
        make.centerX.mas_equalTo(self_weak_.view);
        make.top.mas_equalTo(countDownBgView.mas_bottom).offset(36);
    }];
    
    CGFloat add_top = kYM_NAVIGATIONBAR_HEIGHT+144+36+kWFit(300)+36;
    self.addBtn = [[UIButton alloc]initWithFrame:CGRectMake((kScreenWidth-130)/2.0,add_top,130,42)];
    if((add_top+42+kYM_TABBAR_HEIGHT+30) > kScreenHeight){
        add_top = kScreenHeight-kYM_TABBAR_HEIGHT-30-42;
        self.addBtn.frame =CGRectMake((kScreenWidth-130)/2.0,add_top,130,42);
    }
    if(isIPAD){
        self.addBtn.frame = CGRectMake((self.currentAvailableWidth-130)/2.0,self.currentAvailableHeight-kYM_TABBAR_HEIGHT-42-55,130,42);
    }
    self.addBtn.backgroundColor = KThemeColor;
    [self.addBtn setTitle:@" 添加词书" forState:UIControlStateNormal];
    [self.addBtn setImage:[UIImage imageNamed:@"word_empty_add_logo"] forState:UIControlStateNormal];
    [self.addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.addBtn.titleLabel.font = JPUIFontPingFangBold(16);
    [self.addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addBtn];
    [self.addBtn addCorners:UIRectCornerAllCorners rRadii:42/2.0 shadowLayer:^(CALayer * _Nonnull shadowLayer) {
        shadowLayer.shadowOpacity = 1;
        shadowLayer.shadowOffset = CGSizeMake(0,4);
        shadowLayer.shadowRadius = 10;
        shadowLayer.shadowColor = UIColorHex_(0x15CB9C,0.4).CGColor;
        self_weak_.addShadowLayer = shadowLayer;
    }];
   
    
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        self.addBtn.hidden = YES;
        self.addShadowLayer.hidden = YES;
        self.emptyImageView.hidden = YES;
    }else{
        self.addBtn.hidden = NO;
        self.addShadowLayer.hidden = NO;
        self.emptyImageView.hidden = NO;
    }
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        self.topBgImageView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableWidth);
        CGFloat logo_w = [DeviceUtils getAdaptedWidthForDesignWidth:59 andCurrentAvailableWidth:self.currentAvailableWidth];
        if(logo_w > 59){
            logo_w = 59;
        }
        CGFloat pager_h = [DeviceUtils getAdaptedWidthForDesignWidth:255 andCurrentAvailableWidth:self.currentAvailableWidth];
        CGFloat pager_w = [DeviceUtils getAdaptedWidthForDesignWidth:197 andCurrentAvailableWidth:self.currentAvailableWidth];
        if((self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-171-37-logo_w-37-88) < pager_h){
            pager_h = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-171-37-logo_w-37-88;
            pager_w = 197*pager_h/255;
        }
        self.pagerView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+171,self.currentAvailableWidth,pager_h);
        self.pagerView.itemSize = CGSizeMake(pager_w,pager_h);
        [self.pagerView reloadData];
        CGFloat book_name_w = [DeviceUtils getAdaptedWidthForDesignWidth:240 andCurrentAvailableWidth:self.currentAvailableWidth];
        [self.bookNameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+171+pager_h+32);
            make.width.mas_equalTo(book_name_w);
        }];
        CGFloat progress_w = [DeviceUtils getAdaptedWidthForDesignWidth:200 andCurrentAvailableWidth:self.currentAvailableWidth];
        __weak typeof(self)self_weak_ = self;
        [self.progressView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(progress_w);
            make.top.mas_equalTo(self_weak_.bookNameLabel.mas_bottom).offset(6);
        }];
        [self.precentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self_weak_.progressView.mas_left);
            make.top.mas_equalTo(self_weak_.progressView.mas_bottom).offset(4);
        }];
        [self.countLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self_weak_.progressView.mas_right);
            make.centerY.mas_equalTo(self_weak_.precentLabel);
        }];
       
        CGFloat left = (self.currentAvailableWidth-logo_w*4)/2.0;
        for(NSInteger i = 0;i < 4;i++){
            UIButton *btn = [self.view viewWithTag:233+i];
            [btn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(left+i*logo_w);
                make.height.width.mas_equalTo(logo_w);
                make.top.mas_equalTo(self_weak_.progressView.mas_bottom).offset(37);
            }];
        }
        CGFloat empty_w = [DeviceUtils getAdaptedWidthForDesignWidth:300 andCurrentAvailableWidth:self.currentAvailableWidth];
        if((self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-144-36-42-55-36) < empty_w){
            empty_w = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-144-36-42-55-36;
        }
        [self.emptyImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(empty_w);
        }];
        self.addBtn.frame = CGRectMake((self.currentAvailableWidth-130)/2.0,self.currentAvailableHeight-kYM_TABBAR_HEIGHT-42-55,130,42);
        [self.addShadowLayer removeFromSuperlayer];
        self.addShadowLayer = nil;
        [self.addBtn addCorners:UIRectCornerAllCorners rRadii:42/2.0 shadowLayer:^(CALayer * _Nonnull shadowLayer) {
            shadowLayer.shadowOpacity = 1;
            shadowLayer.shadowOffset = CGSizeMake(0,4);
            shadowLayer.shadowRadius = 10;
            shadowLayer.shadowColor = UIColorHex_(0x15CB9C,0.4).CGColor;
            self_weak_.addShadowLayer = shadowLayer;
        }];
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        if(userId){
            self.addShadowLayer.hidden = YES;
        }else{
            self.addShadowLayer.hidden = NO;
        }
        if(self.deleteAlertView){
            self.deleteAlertView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            self.deleteAlertView.currentAvailableWidth = self.currentAvailableWidth;
            self.deleteAlertView.currentAvailableHeight = self.currentAvailableHeight;
            [self.deleteAlertView refreshWidth];
        }
        if(self.countDownSelView){
            self.countDownSelView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            self.countDownSelView.currentAvailableWidth = self.currentAvailableWidth;
            self.countDownSelView.currentAvailableHeight = self.currentAvailableHeight;
            [self.countDownSelView refreshWidth];
        }
            
        if(self.messageAlertView){
            self.messageAlertView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            self.messageAlertView.currentAvailableWidth = self.currentAvailableWidth;
            self.messageAlertView.currentAvailableHeight = self.currentAvailableHeight;
            [self.messageAlertView refreshWidth];
        }
            
        });
    }
}

#pragma mark - 倒计时设置弹窗
-(void)showTimeSelView{
    if(!self.countDownSelView){
        self.countDownSelView = [[CountDownSelView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight)];
    }
    self.countDownSelView.currentAvailableWidth = self.currentAvailableWidth;
    self.countDownSelView.currentAvailableHeight = self.currentAvailableHeight;
    if(KEY_WINDOW){
        [KEY_WINDOW addSubview:self.countDownSelView];
        [self.countDownSelView selectDateWithFormattedDate:self.timeLabel.text andName:self.countDownTipLabel.text];
        __weak typeof(self)weakSelf = self;
        [self.countDownSelView setSureBlock:^(NSString * _Nonnull timeStr, NSString * _Nonnull nameStr) {
            [weakSelf.countDownSelView removeFromSuperview];
            [weakSelf updateUserInfoWithTimeStr:timeStr andNameStr:nameStr];
        }];
    }
}

#pragma mark - 更新个人信息时间和时间名字
-(void)updateUserInfoWithTimeStr:(NSString*)timeStr andNameStr:(NSString*)nameStr{
    self.editManager.downTime = timeStr;
    self.editManager.downTimeName = nameStr;
    [self.editManager loadData];
}

#pragma mark - 刷新倒计时页面
-(void)refreshCountDownUI{
    if(self.userModel.downTimeName){
        self.countDownTipLabel.text = self.userModel.downTimeName;
    }else{
        NSString *downTimeName = [[NSUserDefaults standardUserDefaults]objectForKey:@"downTimeName"];
        self.countDownTipLabel.text = downTimeName?downTimeName:@"";
    }
    if(self.userModel.downTimeCount){
        self.dayLabel.attributedText = [self changeStr:self.userModel.downTimeCount.integerValue >= 0?self.userModel.downTimeCount:@"0"];
    }else{
        NSString *downTimeCount = [[NSUserDefaults standardUserDefaults]objectForKey:@"downTimeCount"];
        self.dayLabel.attributedText = [self changeStr:downTimeCount?downTimeCount:@"0"];
    }
    if(self.userModel.downTime){
        self.timeLabel.text = self.userModel.downTime;
    }else{
        NSString *downTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"downTime"];
        self.timeLabel.text = downTime?downTime:@"";
    }
}

-(NSMutableAttributedString*)changeStr:(NSString*)str{
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@天",str]];
    [pStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,pStr.length)];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangHeavy(48) range:NSMakeRange(0,str.length)];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangHeavy(15) range:NSMakeRange(str.length,pStr.length-str.length)];
    return pStr;
}

-(NSMutableAttributedString*)changeNameStr:(NSString*)str andStr2:(NSString*)str2{
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@ %@",str,str2]];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangHeavy(17) range:NSMakeRange(0,pStr.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,str.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontGrayColor range:NSMakeRange(str.length,pStr.length-str.length)];
    return pStr;
}

#pragma mark - 日历
-(void)calendarBtnClick{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        StudyCalendarViewController *vc = [[StudyCalendarViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self login];
    }
        
}

#pragma mark - 消息
-(void)msgBtnClick{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        MessageViewController *vc = [[MessageViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self login];
    }
}

#pragma mark - 搜索
-(void)searchBtnClick{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        SearchViewController *vc = [[SearchViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self login];
    }
}

#pragma mark - 删除 背 测 添加
-(void)btnClick:(UIButton*)button{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        NSInteger index = button.tag-233;
        if(index == 0){
            //删除
            [self showDeleteAlertView];
        }else if (index == 1){
            //背
            CourseListViewController *vc = [[CourseListViewController alloc]init];
            vc.bookModel = self.currentBookModel;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (index == 2){
            //测
            TestWordChooseCourseViewController *vc = [[TestWordChooseCourseViewController alloc]init];
            vc.bookListModel = self.currentBookModel;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            //添加
            BookListViewController *vc = [[BookListViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        [self login];
    }
}

#pragma mark - 删除
-(void)showDeleteAlertView{
    if(!self.deleteAlertView){
        self.deleteAlertView = [[TestSubmitAlertView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, self.currentAvailableHeight) andTitle:@"确定删除本词书吗？" andLeftTitle:@"取消" andleftColor:KFontBlackColor andRightTitle:@"确定" andRightColor:KThemeColor andTitleFont:JPUIFontPingFangSCMedium(16) andLeftFont:JPUIFontPingFangSCRegular(16) andRightFont:JPUIFontPingFangSCMedium(16)];
    }
    self.deleteAlertView.currentAvailableWidth = self.currentAvailableWidth;
    self.deleteAlertView.currentAvailableHeight = self.currentAvailableHeight;
    UIWindow *window = KEY_WINDOW;
    if(window){
        [window addSubview:self.deleteAlertView];
    }
    __weak typeof(self)self_weak_  = self;
    [self.deleteAlertView setLeftBlock:^{
        [self_weak_.deleteAlertView removeFromSuperview]; 
    }];
    [self.deleteAlertView setRightBlock:^{
        [self_weak_.deleteAlertView removeFromSuperview];
        self_weak_.deleteBookManager.ubId = self_weak_.currentBookModel.ubId;
        [self_weak_.deleteBookManager loadData];
    }];
    
}

#pragma mark - 添加词书
-(void)addBtnClick{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        BookListViewController *vc = [[BookListViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self login];
    }
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - FSPagerViewDataSource
- (NSInteger)numberOfItemsInPagerView:(FSPagerView *)pagerView{
    return self.bookArr.count;
}

- (FSPagerViewCell *)pagerView:(FSPagerView *)pagerView cellForItemAtIndex:(NSInteger)index{
    FSPagerViewCell * cell = [pagerView dequeueReusableCellWithReuseIdentifier:@"BookCell" atIndex:index];
    if(index < self.bookArr.count){
        MyBookListModel *model = self.bookArr[index];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.path]];
    }
    return cell;
}

#pragma mark - FSPagerViewDelegate
- (void)pagerView:(FSPagerView *)pagerView didSelectItemAtIndex:(NSInteger)index{
    [pagerView deselectItemAtIndex:index animated:YES];
    [pagerView scrollToItemAtIndex:index animated:YES];
    if(index < self.bookArr.count){
        MyBookListModel *model = self.bookArr[index];
        CourseListViewController *vc = [[CourseListViewController alloc]init];
        vc.bookModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)pagerViewDidEndDecelerating:(FSPagerView *)pagerView{
    NSInteger currentIndex = pagerView.currentIndex;
    NSLog(@"滑动结束，当前的索引为：%ld", (long)currentIndex);
    // 在这里处理滑动结束后的操作
    [self refreshBookUIWithIndex:currentIndex];
}



#pragma mark - 刷新书的显示
-(void)refreshBookUIWithIndex:(NSInteger)index{
     if(index < self.bookArr.count){
         MyBookListModel *model = self.bookArr[index];
         self.currentBookModel = model;
         self.bookNameLabel.attributedText = [self changeNameStr:model.name andStr2:model.volumeName];
         CGFloat p = 0;
         if(model.sumNumber&&model.learnedNumber){
             if(model.sumNumber.integerValue > 0){
                 p = model.learnedNumber.floatValue/model.sumNumber.floatValue;
             }
         }
         self.progressView.progress = p;
         self.precentLabel.text = [NSString stringWithFormat:@"%.f%%",p*100];
         self.countLabel.text = [NSString stringWithFormat:@"%@/%@",model.learnedNumber,model.sumNumber];
     }
}

#pragma mark - 没有书本的显示
-(void)refreshAddBookView{
    self.addShadowLayer.hidden = NO;
    self.addBtn.hidden = NO;
    self.emptyImageView.hidden = NO;
    self.pagerView.hidden = YES;
    self.bookNameLabel.hidden = YES;
    self.progressView.hidden = YES;
    self.precentLabel.hidden = YES;
    self.countLabel.hidden = YES;
    for(NSInteger i = 0;i < 4;i++){
        UIButton *btn = [self.view viewWithTag:233+i];
        btn.hidden = YES;
    }
}


#pragma mark - 最新消息弹窗
-(void)showMsgAlertViewWithModel:(NewsListModel*)model{
    NSString *newsId = [NSString stringWithFormat:@"%@",model.newsId];
    NSString *newsId2 = [[NSUserDefaults standardUserDefaults]objectForKey:@"HomeAlertMsgId"];
    if(!(newsId2&&[newsId2 isEqualToString:newsId])){
        if(!self.messageAlertView){
            self.messageAlertView = [[MessageAlertView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, self.currentAvailableHeight) andModel:model];
        }
        self.messageAlertView.currentAvailableWidth = self.currentAvailableWidth;
        self.messageAlertView.currentAvailableHeight = self.currentAvailableHeight;
        self.messageAlertView.model = model;
        if(KEY_WINDOW){
            [KEY_WINDOW addSubview:self.messageAlertView];
            __weak typeof(self)weakSelf = self;
            [self.messageAlertView setClickBlock:^{
                [weakSelf.messageAlertView removeFromSuperview];
                if(model.newsId){
                    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",model.newsId] forKey:@"HomeAlertMsgId"];
                }
            }];
        }
    }
}

#pragma mark - 获取app store版本号
-(void)getAppVersion{
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",JPAPPID]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSError *jsonError;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
            if (!jsonError) {
                NSArray *results = json[@"results"];
                if (results.count > 0) {
                    NSDictionary *appInfo = results.firstObject;
                    NSString *storeVersion = appInfo[@"version"];
                    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
                    BOOL isVersionEqual = [storeVersion isEqualToString:currentVersion];
                    if (isVersionEqual) {
                        NSLog(@"当前版本与 App Store 版本一致");
                        dispatch_async(dispatch_get_main_queue(), ^{
                        [JPProgressHUD showMsg:@"当前已是最新版本"];
                        });
                    } else {
                        NSLog(@"当前版本与 App Store 版本不一致");
                        dispatch_async(dispatch_get_main_queue(), ^{
                            // 去更新
                            NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                            if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                                [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                            }
                        });
                    }
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                        if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                            [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                        }
                    });
                }
            } else {
                NSLog(@"解析 JSON 错误: %@", jsonError.localizedDescription);
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                    if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                        [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                    }
                });
            }
        } else {
            NSLog(@"请求 App Store 信息失败: %@", error.localizedDescription);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
                if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
                    [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
                }
            });
        }
    }];
    [dataTask resume];
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.myBookListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr  = [MyBookListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.bookArr addObjectsFromArray:arr];
        [self.pagerView reloadData];
        if(arr.count > 0){
            if(arr.count >= 3){
                self.pagerView.isInfinite = YES;
            }else{
                self.pagerView.isInfinite = NO;
            }
            self.addBtn.hidden = YES;
            self.addShadowLayer.hidden = YES;
            self.emptyImageView.hidden = YES;
            self.pagerView.hidden = NO;
            self.bookNameLabel.hidden = NO;
            self.progressView.hidden = NO;
            self.precentLabel.hidden = NO;
            self.countLabel.hidden = NO;
            for(NSInteger i = 0;i < 4;i++){
                UIButton *btn = [self.view viewWithTag:233+i];
                btn.hidden = NO;
            }
            if(self.book_index&&self.book_index < arr.count){
                [self refreshBookUIWithIndex:self.book_index];
                self.book_index = 0;
            }else{
                [self refreshBookUIWithIndex:0];
            }
        }else{
            [self refreshAddBookView];
        }
    }
    
    if([manager isEqual:self.deleteBookManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [self.bookArr removeObject:self.currentBookModel];
        if(self.bookArr.count >= 3){
            self.pagerView.isInfinite = YES;
        }else{
            self.pagerView.isInfinite = NO;
        }
        [self.pagerView reloadData];
        if(self.bookArr.count > 0){
            [self refreshBookUIWithIndex:0];
        }else{
            [self refreshAddBookView];
        }
    }
    
    
    if([manager isEqual:self.userInfoManager]){
        NSDictionary *dic = manager.response.content;
        self.userModel = [MineUserModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.userModel.userId){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.userId forKey:@"userId"];
        }
        if(self.userModel.phone){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.phone forKey:@"phone"];
        }
        if(self.userModel.nickname){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.nickname forKey:@"nickname"];
        }
        if(self.userModel.avatar){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.avatar forKey:@"avatar"];
        }
        if(self.userModel.sex){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.sex forKey:@"sex"];
        }
        if(self.userModel.introduction){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.introduction forKey:@"introduction"];
        }
        if(self.userModel.goldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.goldNumber forKey:@"goldNumber"];
        }
        
        if(self.userModel.signCount){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.signCount forKey:@"signCount"];
        }
        
        if(self.userModel.downTime){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTime forKey:@"downTime"];
        }
        
        if(self.userModel.downTimeName){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTimeName forKey:@"downTimeName"];
        }
        
        if(self.userModel.downTimeCount){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTimeCount forKey:@"downTimeCount"];
        }
        
        if(self.userModel.wordNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.wordNumber forKey:@"wordNumber"];
        }
        
        if(self.userModel.mode){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.mode forKey:@"mode"];
        }
        
        if(self.userModel.addGoldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.addGoldNumber forKey:@"addGoldNumber"];
        }
        
        [self refreshCountDownUI];
        
    }
    
    if([manager isEqual:self.editManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        self.userModel = [MineUserModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.userModel.downTime){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTime forKey:@"downTime"];
        }
        
        if(self.userModel.downTimeName){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTimeName forKey:@"downTimeName"];
        }
        
        if(self.userModel.downTimeCount){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTimeCount forKey:@"downTimeCount"];
        }
        [self refreshCountDownUI];
        
    }
    
    if([manager isEqual:self.downTimeManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"data"][@"downTime"]){
            [[NSUserDefaults standardUserDefaults]setObject:dic[@"data"][@"downTime"] forKey:@"downTime"];
        }
        
        if(dic[@"data"][@"downTimeName"]){
            [[NSUserDefaults standardUserDefaults]setObject:dic[@"data"][@"downTimeName"] forKey:@"downTimeName"];
        }
        
        if(dic[@"data"][@"downTimeCount"]){
            [[NSUserDefaults standardUserDefaults]setObject:dic[@"data"][@"downTimeCount"] forKey:@"downTimeCount"];
        }
        [self refreshCountDownUI];
    }
    
    if([manager isEqual:self.newsCheckManager]){
        NSDictionary *dic = manager.response.content;
        NSString *isRead = [NSString stringWithFormat:@"%@",dic[@"data"][@"isRead"]];
        if(isRead.integerValue == 1){
            self.point.hidden = NO;
        }else{
            self.point.hidden = YES;
        }
    }
    
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
    }
    
    
    if([manager isEqual:self.msgListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [NewsListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"list"]];
        if(arr.count > 0){
            NewsListModel *model = arr[0];
            [self showMsgAlertViewWithModel:model];
        }
    }
    
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(!([manager isEqual:self.newsCheckManager]||[manager isEqual:self.msgListManager])){
        if(manager.errorMessage){
            [JPProgressHUD showMsg:manager.errorMessage];
        }
    }
}

#pragma mark - 获取token
-(BOOL)checkToken{
    BOOL isneedget = NO;
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                isneedget = YES;
                [self.aLiYunTokenManager loadData];
            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            isneedget = YES;
            [self.aLiYunTokenManager loadData];

        }
    }else{
        isneedget = YES;
        [self.aLiYunTokenManager loadData];

    }
    return isneedget;
}



-(void)dealloc{
    if (self.reachability){
           SCNetworkReachabilityUnscheduleFromRunLoop(self.reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
           CFRelease(self.reachability);
           self.reachability = nil;
    }
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    if(self.timer){
        [self.timer invalidate];
        self.timer = nil;
    }
}

@end
